package sh.ds.el.dao.jdbc;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import sh.ds.el.common.Constants;

public class DefaultSqlExceution {

	private DataSource dataSource;
	
	private JdbcTemplate jdbcTemplate;
	
	private static RowMapper OBJECT_ARRAY_MAPPER = new ObjectArrayRowMapper();
	
	public DefaultSqlExceution(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(this.dataSource);
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> queryForListBySql(Class<T> returnType, String sql, List<Object> params, RowMapper rowMapper, Pagination pagination) {
		Object[] args = Constants.EMPTY_OBJECT_ARRAY;
		if (params != null) {
			args = params.toArray();
		}
		if (pagination == null) {
			return jdbcTemplate.query(sql, args, rowMapper);
		}
		
		return null;
	}
	
	public <T> List<T> queryForListBySql(Class<T> returnType, String sql, List<Object> params) {
		return queryForListBySql(returnType, sql, params, OBJECT_ARRAY_MAPPER, null);
	}
	
	public <T> List<T> queryForWrapBeanListBySql(Class<T> returnType, String sql, List<Object> params) {
		return queryForListBySql(returnType, sql, params, new BeanPropertyRowMapper(returnType), null);
	}

}
